'''
tiff 文件读写
https://blog.csdn.net/t46414704152abc/article/details/77482747
'''
from osgeo import gdal
import numpy as np
from matplotlib import pyplot as plt
import os
import shutil
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import pandas as pds 
import json
import shutil


def ReadRSImg(imgpath):
    dataset=gdal.Open(imgpath)
    im_width=dataset.RasterXSize # 列数
    im_height=dataset.RasterYSize # 行数
    im_bands=dataset.RasterCount # 波段数
    im_geotrans=dataset.GetGeoTransform() # 仿射矩阵
    im_proj=dataset.GetProjection() # 地图投影信息
    # 数据文件
    data=np.zeros((im_height,im_width,im_bands))
    for i in range(im_bands):
        sigBandData=dataset.GetRasterBand(i+1)
        sigBandData_arr=sigBandData.ReadAsArray(0,0,im_width,im_height)
        data[:,:,i]=sigBandData_arr
    return data,im_geotrans,im_proj,dataset


if __name__=='__main__':
        # 确定影像数据集的位置
    gf2_nanchang_path='/media/gis/databackup/ayc/modellist/dataset/tifData/bandhechengTIF.tif' 
    train_gf2_data_path='/media/gis/databackup/ayc/modellist/dataset/tifData/train_Mask_bandhechengTIF.tif' 
    traindataset="/media/gis/databackup/ayc/modellist/dataset/nanchang"
    data,im_geotrans,im_proj,dataset=ReadRSImg(gf2_nanchang_path)
    # 分离mask和data
    mask=data[:,:,0]
    gf2data=data[:,:,1:]
    # 记录每个波段的线性拉伸值
    minvalues=np.array([
        np.percentile(gf2data[:,:,0],2),
        np.percentile(gf2data[:,:,1],2),
        np.percentile(gf2data[:,:,2],2),
        np.percentile(gf2data[:,:,3],2)
    ])
    maxvalues=np.array([
        np.percentile(gf2data[:,:,0],98),
        np.percentile(gf2data[:,:,1],98),
        np.percentile(gf2data[:,:,2],98),
        np.percentile(gf2data[:,:,3],98),
    ])
    data=data/1000
    data=np.clip(data,0,255)
    # 数据的基本信息
    plt.imshow(data[:,:,:3])
    plt.show()